import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 *  编写代码, 实现线程池案例
 */

class  MyThreadPool {
    final private BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();

    public void submit(Runnable runnable) throws InterruptedException {
        // 添加任务
        queue.put(runnable);
    }

    public MyThreadPool(int m) {
        // 创建m个线程来完成任务.
        for (int i = 0; i < m; i++) {
            Thread t = new Thread(() -> {
                while (true) {
                    try {
                        Runnable runnable = queue.take();
                        runnable.run();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            t.start();
        }

    }
}

public class Test3 {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPool pool = new MyThreadPool(10); // m 个线程

        for (int i = 0; i < 1000; i++) {
            // 添加 1000 个任务
            int k = i;
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("当前执行任务: " + k + "  当前线程: " + Thread.currentThread().getName());
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

    }
}
